/* ************************************************************************
> File Name:     intlist.c
> Author:        zhfu
> mail:          3346897597@qq.com
> Created Time:  2022年05月04日 星期三 22时15分15秒
> Description:   
 ************************************************************************/
#include<stdlib.h>
#include<stdio.h>
#include"intlist.h"

static link make_node(int item)
{
    link p = malloc(sizeof *p);
    p->item = item;
    p->next = NULL;

    return p;
}

static void free_node(link p)
{
    free(p);
}

void list_insert(intlist *l, int item)
{
    if (!l->head){
        l->head = make_node(item);
        return;
    }

    link p = make_node(item);
    p->next = l->head;
    l->head = p;
}

void list_delete(intlist *l, int item)
{
    link p = l->head;
    if (p->item == item){
        l->head = p->next;
        free_node(p);
        return;
    }

    link q = l->head;
    p = q->next;
    while (p){
        if (p->item == item){
            q->next = p->next;
            free_node(p);
        }
        q = p;
        p = p->next;
    }
}

link list_search(intlist *l, int item)
{
    link p = l->head;
    while (p){
        if (p->item == item){
            return p;
        }
        p = p->next;
    }
    return NULL;
}

void print_list(intlist *l)
{
    link p = l->head;
    while (p){
        printf("%d ", p->item);
        p = p->next;
    }
    putchar('\n');
}

void free_list(intlist *l)
{
    link p = l->head;
    if (p){
        link n = p->next;
        while (p){
            free_node(p);
            p = n;
            if (!n){
                break;
            }
            else{
                n = n->next;
            }
        }
    }
}

int get_list_size(intlist *l)
{
    int i = 0;
    link p = l->head;

    while (p){
        ++i;
        p = p->next;
    }

    return i;
}
